package com.dfwl.packageio.core.db;


import com.dfwl.packageio.App;
import com.dfwl.packageio.core.base.EntityBase;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;


public abstract class AbsDbOperation implements IDbOperation{

	public DbRepository getDbManager(){
		return App.getInstance().getDbManager();
	}
	@Override
	public boolean saveData(EntityBase mEntity) {
		
		try {
			getDbManager().getContentDb().save(mEntity);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	
	public abstract String  getDbName ();
	@Override
	public boolean deleteDataFromDb(String sql) {
		try {
			getDbManager().getContentDb().execNonQuery(sql);
			return true;
		} catch (DbException e) {
			return false;
		}
	}
	@Override
	public boolean updateDataFromDb(String sql) {
		try {
			getDbManager().getContentDb().execNonQuery(sql);
			return true;
		} catch (DbException e) {
			return false;
		}
	}
	
	public void clearDbData() {
	        try {
				  getDbManager().getContentDb().execNonQuery("delete from "+ getDbName());
	        } catch (DbException e) {
	            e.printStackTrace();
	        }
	    }
	 
	public void insertOrUpdate(EntityBase mUser,WhereBuilder mWhereBuilder){
	        boolean isInsertSuccess = saveData(mUser);
	        if (!isInsertSuccess) {
	            try {
						getDbManager().getContentDb()
	                        .update(mUser, mWhereBuilder);
	            } catch (DbException e) {
	            }
	        }
	    }
}
